<script setup lang="ts">
import type { ComponentOptions, componentType } from './componentPanel/index'
import type { Fullscreen } from '@/components/LayoutForm/src/type'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import ComponentPanel from './componentPanel/index.vue'
import FormConfig from './formConfig/index.vue'
import FormGenerator from './formGenerator/index.vue'

const panelComponents = ref<ComponentOptions[]>([])
const selectComponent = ref<ComponentOptions>({
  id: '',
  component: '',
  span: 12,
  label: '',
  labelWidth: '100px',
  field: '',
  defaultValue: '',
  attrs: '{}',
})

const formBasicConfig = ref({
  totalColumns: 24,
  gridGap: 4,
  description: '这是一个表单',
})

provide('formBasicConfig', formBasicConfig)
provide('selectComponent', selectComponent)
provide('componentsPanel', panelComponents)

function handleSelectComponent(component: componentType) {
  selectComponent.value = component.options
}

const currentDraggingComponent = ref<ComponentOptions | null>()
function handleDragStart(component: ComponentOptions) {
  currentDraggingComponent.value = component
}
function handleDrop(newDraggableIndex: number) {
  if (currentDraggingComponent.value) {
    panelComponents.value.splice(newDraggableIndex, 0, cloneDeep(currentDraggingComponent.value))
    currentDraggingComponent.value = null
  }
}

function removeField(index: number) {
  panelComponents.value.splice(index, 1)
}
const fullscreenRef = ref()
provide<Fullscreen>('fullscreen', {
  Ref: fullscreenRef,
  handleFullscreen,
})
function handleFullscreen() {
  if (fullscreenRef.value) {
    fullscreenRef.value.requestFullscreen()
  }
}
</script>

<template>
  <div ref="fullscreenRef" class="flex justify-between h-full bg-[#f5f7fa]">
    <div class="w-[230px] px-[20px] py-[15px] bg-white">
      <ComponentPanel @handle-drag-start="handleDragStart" />
    </div>
    <div class="flex-1 h-full relative ">
      <div class="mx-[20px] py-[15px] px-[20px] bg-white h-full">
        <FormGenerator @drag-add="handleDrop" @remove-field="removeField" @select-component="handleSelectComponent" />
      </div>
    </div>
    <div class="w-[350px] px-[20px] py-[15px] bg-white">
      <FormConfig />
    </div>
  </div>
</template>
